/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.xxhong.xxtv;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.DetailsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.util.DisplayMetrics;
import android.util.Log;

import com.xxhong.xxtv.activity.DetailsActivity;
import com.xxhong.xxtv.activity.MainActivity;
import com.xxhong.xxtv.domain.Poems;
import com.xxhong.xxtv.presenter.PoemDetailPresenter;
import com.xxhong.xxtv.service.MovieList;

import java.util.Collections;
import java.util.List;

/*
 * LeanbackDetailsFragment extends DetailsFragment, a Wrapper fragment for leanback details screens.
 * It shows a detailed view of video and its meta plus related videos.
 */
public class VideoDetailsFragment extends DetailsFragment {
    private static final String TAG = "VideoDetailsFragment";

    private static final int ACTION_WATCH_TRAILER = 1;
    private static final int ACTION_RENT = 2;
    private static final int ACTION_BUY = 3;


    private static final int NUM_COLS = 10;

    private Poems mSelectedMovie;

    private ArrayObjectAdapter mAdapter;

    private BackgroundManager mBackgroundManager;
    private Drawable mDefaultBackground;
    private DisplayMetrics mMetrics;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate DetailsFragment");
        super.onCreate(savedInstanceState);

        prepareBackgroundManager();
        mSelectedMovie = (Poems) getActivity().getIntent()
                .getSerializableExtra(DetailsActivity.MOVIE);
        if (mSelectedMovie != null) {
            PoemDetailPresenter poemsPresenter = new PoemDetailPresenter();
            mAdapter = new ArrayObjectAdapter(poemsPresenter);
            mAdapter.add(mSelectedMovie);
//            final DetailsOverviewRow row = new DetailsOverviewRow(mSelectedMovie);
//            row.setImageDrawable(getResources().getDrawable(R.drawable.default_background));
//            row.addAction(new Action(ACTION_WATCH_TRAILER, getResources().getString(
//                    R.string.watch_trailer_1), getResources().getString(R.string.watch_trailer_2)));
//            row.addAction(new Action(ACTION_RENT, getResources().getString(R.string.rent_1),
//                    getResources().getString(R.string.rent_2)));
//            row.addAction(new Action(ACTION_BUY, getResources().getString(R.string.buy_1),
//                    getResources().getString(R.string.buy_2)));
//            mAdapter.add(new ListRow(arrayObjectAdapter));
            setAdapter(mAdapter);
//            setupDetailsOverviewRow();
//            setupDetailsOverviewRowPresenter();
//            setupMovieListRow();
//            setupMovieListRowPresenter();
//            updateBackground(mSelectedMovie.getBackgroundImageUrl());
            setOnItemViewClickedListener(new ItemViewClickedListener());
        } else {
            Intent intent = new Intent(getActivity(), MainActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void prepareBackgroundManager() {
        mBackgroundManager = BackgroundManager.getInstance(getActivity());
        mBackgroundManager.attach(getActivity().getWindow());
        mDefaultBackground = getResources().getDrawable(R.drawable.default_background);
        mMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
    }



//    private void setupDetailsOverviewRow() {
//        Log.d(TAG, "doInBackground: " + mSelectedMovie.toString());

//        Glide.with(getActivity())
//                .load(mSelectedMovie.getCardImageUrl())
//                .centerCrop()
//                .error(R.drawable.default_background)
//                .into(new SimpleTarget<GlideDrawable>(width, height) {
//                    @Override
//                    public void onResourceReady(GlideDrawable resource,
//                                                GlideAnimation<? super GlideDrawable>
//                                                        glideAnimation) {
//                        Log.d(TAG, "details overview card image url ready: " + resource);
//                        row.setImageDrawable(resource);
//                        mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
//                    }
//                });



//    }

//    private void setupDetailsOverviewRowPresenter() {
        // Set detail background and style.
//        DetailsOverviewRowPresenter detailsPresenter =
//                new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter());
//        detailsPresenter.setBackgroundColor(getResources().getColor(R.color.selected_background));
//        detailsPresenter.setStyleLarge(true);
//
//        // Hook up transition element.
////        detailsPresenter.setSharedElementEnterTransition(getActivity(),
////                DetailsActivity.SHARED_ELEMENT_NAME);
//
//        detailsPresenter.setOnActionClickedListener(new OnActionClickedListener() {
//            @Override
//            public void onActionClicked(Action action) {
//                if (action.getId() == ACTION_WATCH_TRAILER) {
//
//                } else {
//                    Toast.makeText(getActivity(), action.toString(), Toast.LENGTH_SHORT).show();
//                }
//            }
//        });

//    }

//    class  PoemsPresenter extends Presenter{
//
//        @Override
//        public ViewHolder onCreateViewHolder(ViewGroup parent) {
//            LayoutInflater lf = LayoutInflater.from(parent.getContext());
//            View view = lf.inflate(R.layout.poem_detail, null);
//            return new ViewHolder(view);
//        }
//
//        @Override
//        public void onBindViewHolder(ViewHolder viewHolder, Object item) {
//            TextView title,author,content;
//            View v = viewHolder.view;
//            Poems poems = (Poems)item;
//            title = (TextView) v.findViewById(R.id.tv_title);
//            author = (TextView) v.findViewById(R.id.tv_author);
//            content = (TextView) v.findViewById(R.id.tv_content);
//            title.setText(poems.getTitle());
//            author.setText(poems.getAuthor());
//            String[] split = poems.getContent().split("。");
//            StringBuilder sb = new StringBuilder();
//            for(int i=0;i<split.length;i++){
//                String s = split[i];
//                sb.append(s+"。\n");
//            }
//            content.setText(sb.toString());
//        }
//
//        @Override
//        public void onUnbindViewHolder(ViewHolder viewHolder) {
//
//        }
//    }

    private void setupMovieListRow() {
        String subcategories[] = {getString(R.string.related_movies)};
        List<Poems> list = MovieList.list;

        Collections.shuffle(list);
        ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter());
        for (int j = 0; j < NUM_COLS; j++) {
            listRowAdapter.add(list.get(j % 5));
        }

        HeaderItem header = new HeaderItem(0, subcategories[0]);
        mAdapter.add(new ListRow(header, listRowAdapter));
    }

//    private void setupMovieListRowPresenter() {
//        mPresenterSelector.addClassPresenter(ListRow.class, new ListRowPresenter());
//    }

    private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Poems) {
//                Poems movie = (Poems) item;
//                Log.d(TAG, "Item: " + item.toString());
//                Intent intent = new Intent(getActivity(), DetailsActivity.class);
//                intent.putExtra(getResources().getString(R.string.movie), mSelectedMovie);
//                intent.putExtra(getResources().getString(R.string.should_start), true);
//                startActivity(intent);
//
//
//                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
//                        getActivity(),
//                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
//                        DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
//                getActivity().startActivity(intent, bundle);
            }
        }
    }
}
